const { request } = require('../../../utils/http');
const API_BASE = 'https://tihaidengta.xyz/api';
Page({
  data: {
    questions: [],
    currentIndex: 0,
    showExplanation: false,
    userAnswer: '',
    showResult: false,
    correctCount: 0,
    isLoading: false ,// 防止重复请求
    answeredQuestions: [] // 记录已答题目索引
  },

  onLoad(options) {
    const bankId = options.bankId || 1390; // 支持URL传参
    this.fetchQuestions(bankId);
  },

  // 优化的请求方法（带防抖/错误处理）
  fetchQuestions(bankId) {
    if (this.data.isLoading) return;
    this.setData({ isLoading: true });
  
    wx.showLoading({ title: '加载题目中...', mask: true });
  
    request({
      url: `${API_BASE}/question/bankXcx/${bankId}/1/20`,
      method: 'POST',
    }).then(res => {
      console.log('[题库接口响应]', res);
  
      if (!res || !res.data) {
        return wx.showToast({ title: '加载失败，请检查服务器', icon: 'none' });
      }
  
      const { data } = res;
  
      this.setData({
        questions: data.list.map(q => ({
          questionId: q.questionId,
          content: (q.content || '').replace(/\$/g, ''),
          explanation: (q.explanation || '').replace(/\n/g, '<br>'),
          answer: q.answer,
          optionsArray: [
            { key: 'A', text: q.a.replace(/\$/g, '') },
            { key: 'B', text: q.b.replace(/\$/g, '') },
            { key: 'C', text: q.c.replace(/\$/g, '') },
            { key: 'D', text: q.d.replace(/\$/g, '') }
          ]
        })),
        total: data.total
      });
    }).catch(err => {
      console.error('[网络错误]', err);
      wx.showToast({ title: '请求失败，请检查网络', icon: 'none', duration: 2000 });
    }).finally(() => {
      this.setData({ isLoading: false });
      wx.hideLoading();
    });
  },
  

  onSelect(e) {
    const { value } = e.detail;
    const currentQuestion = this.data.questions[this.data.currentIndex];
  
    if (value === currentQuestion.answer) {
      // 答对：1秒后自动跳转
      this.setData({
        userAnswer: value,
        showResult: true,
        showExplanation: false, // 不显示解析
        answeredQuestions: [...new Set([...this.data.answeredQuestions, this.data.currentIndex])]
      });
  
      setTimeout(() => {
        this.setData({ showResult: false }); // 先隐藏“下一题”按钮，避免重复
        this.nextQuestion();
      }, 1000);
    } else {
      // 答错：显示解析，停留在当前题目
      this.setData({
        userAnswer: value,
        showResult: true,
        showExplanation: true, // 显示解析
        answeredQuestions: [...new Set([...this.data.answeredQuestions, this.data.currentIndex])]
      });
    }
  },
  changeQuestion(e) {
    const { index } = e.detail;
    this.setData({
      currentIndex: index,
      showResult: false,
      showExplanation: false,
      userAnswer: ''
    });
  },
  toggleExplanation() {
    this.setData({ showExplanation: !this.data.showExplanation });
  },

 nextQuestion() {
  const nextIndex = this.data.currentIndex + 1;
  if (nextIndex < this.data.questions.length) {
    this.setData({
      currentIndex: nextIndex,
      showResult: false, // 确保进入下一题后隐藏“下一题”按钮
      showExplanation: false,
      userAnswer: ''
    });
  }
},


  finishPractice() {
    wx.showModal({
      title: '练习完成',
      content: `共${this.data.questions.length}题，答对${this.data.correctCount}题\n正确率：${((this.data.correctCount / this.data.questions.length) * 100).toFixed(1)}%`,
      success: (res) => {
        if (res.confirm) {
          wx.navigateBack();
        }
      }
    });
  },

  // 新增：下拉刷新
  onPullDownRefresh() {
    this.fetchQuestions(this.data.questions[0]?.bankId || 1390);
    wx.stopPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
});